<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import {
  postLoginWxMinAPI,
  postLoginWxMinSimpleAPI,
  postLoginAPI,
} from '@/services/login'
import { useMemberStore } from '@/stores'
import type { LoginResult } from '@/types/member'
import { ref } from 'vue'
// #ifdef MP-WEIXIN
// 获取code 登录凭证
let code = ''
onLoad(async () => {
  const res = await wx.login()
  code = res.code
})

// 获取用户手机号码（企业中写法）
const onGetphonenumber: UniHelper.ButtonOnGetphonenumber = async (ev) => {
  try {
    const encryptedData = ev.detail!.encryptedData!
    const iv = ev.detail!.iv!
    const res = await postLoginWxMinAPI({
      code,
      encryptedData,
      iv,
    })
    loginSuccess(res.result)
  } catch (err) {
    console.log(err)
  }
}
// #endif

// 模拟手机号码快捷登录（开发练习）
const onGetphonenumberSimple = async () => {
  const res = await postLoginWxMinSimpleAPI('17875695147')
  loginSuccess(res.result)
}

const loginSuccess = (profile: LoginResult) => {
  // 保存会员信息
  const memberStore = useMemberStore()
  memberStore.setProfile(profile)

  // 成功提示
  uni.showToast({
    icon: 'success',
    title: '登录成功',
    mask: true,
  })

  // 页面跳转
  setTimeout(() => {
    // uni.switchTab({
    //   url: '/pages/my/my',
    // })
    uni.navigateBack()
  }, 500)
}

// #ifdef APP-PLUS || H5
// 传统登录

const form = ref({
  account: '13123456789',
  password: '123456',
})

// 表单校验规则
const relus: UniHelper.UniFormsRules = {
  account: {
    rules: [{ required: true, errorMessage: '请输入用户名/手机号码' }],
  },
  password: {
    rules: [
      {
        required: true,
        errorMessage: '请输入密码',
      },
    ],
  },
}

// 获取表单实例
const formRef = ref<UniHelper.UniFormsInstance>()

const login = async () => {
  try {
    await formRef.value?.validate?.()
    const res = await postLoginAPI(form.value)
    loginSuccess(res.result)
  } catch (e) {
    console.log(e)
  }
}
// #endif
</script>

<template>
  <view class="viewport">
    <view class="logo">
      <image
        src="https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/logo_icon.png"
      ></image>
    </view>
    <view class="login">
      <!-- #ifdef MP-WEIXIN -->
      <button
        class="button phone"
        open-type="getPhoneNumber"
        @getphonenumber="onGetphonenumber"
      >
        <text class="icon icon-phone"></text>
        手机号快捷登录
      </button>
      <!-- #endif -->

      <!-- #ifdef APP-PLUS || H5 -->
      <uni-forms ref="formRef" :model="form" :rules="relus">
        <uni-forms-item name="account">
          <input
            class="input"
            v-model="form.account"
            type="text"
            placeholder="请输入用户名/手机号"
          />
        </uni-forms-item>
        <uni-forms-item name="password">
          <input
            class="input"
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
          />
        </uni-forms-item>
        <button @click="login" class="login-btn">登录</button>
      </uni-forms>
      <!-- #endif -->

      <view class="extra">
        <view class="caption">
          <text>其他登录方式</text>
        </view>
        <view class="options">
          <button @tap="onGetphonenumberSimple">
            <text class="icon icon-phone">模拟快捷登录</text>
          </button>
        </view>
      </view>
      <view class="tips"
        >登录/注册即视为你同意《服务条款》和《小兔鲜儿隐私协议》</view
      >
    </view>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
}

.logo {
  flex: 1;
  text-align: center;
  image {
    width: 220rpx;
    height: 220rpx;
    margin-top: 15vh;
  }
}

.login {
  display: flex;
  flex-direction: column;
  height: 60vh;
  padding: 40rpx 20rpx 20rpx;

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    color: #fff;
    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .phone {
    background-color: #28bb9c;
  }

  .wechat {
    background-color: #06c05f;
  }

  .extra {
    flex: 1;
    padding: 70rpx 70rpx 0;
    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #999;
      position: relative;
      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;
      button {
        padding: 0;
        background-color: transparent;
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }
    .icon-weixin::before {
      border-color: #06c05f;
      color: #06c05f;
    }
  }

  /* #ifdef APP-PLUS || H5 */
  .uni-forms-item {
    margin-bottom: 30rpx;
    .input {
      height: 80rpx;
      padding: 0 30rpx;
      font-size: 28rpx;
      border: 1px solid #ccc;
      border-radius: 40rpx;
    }
  }
  .login-btn {
    height: 80rpx;
    background-color: #1bac9d;
    line-height: 80rpx;
    font-size: 28rpx;
    color: #fff;
    border-radius: 40rpx;
  }
  /* #endif */
}

.tips {
  position: absolute;
  bottom: 80rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;
}
</style>
